package com.bcx.wind.workflow.core.lock;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 同数据锁
 *
 * @author zhanglei
 */
public class WindLock implements com.bcx.wind.workflow.core.lock.Lock {

    /**
     * 锁容器
     */
    private static ConcurrentHashMap<String,ReentrantLock>  locks = new ConcurrentHashMap<>();

    /**
     * 获取同步锁  如果操作的数据key 锁已经存在，则直接获取已经存在的锁，否则创建一把新锁
     *
     * @param key  键
     * @return      lock
     */
    private static ReentrantLock  getLock(String key){
        ReentrantLock lock = new ReentrantLock();
        ReentrantLock preLock = locks.putIfAbsent(key,lock);
        return preLock == null ? lock : preLock;
    }

    @Override
    public void lock(Object key) {
        Lock lock = getLock(key.toString());
        lock.lock();
    }

    @Override
    public void unlock(Object key) {
        ReentrantLock lock = getLock(key.toString());
        if(lock.isHeldByCurrentThread()){
            lock.unlock();
        }
    }
}
